/* UPVS 2
 * Copyright (c) Martin Kumst 2011
 * Licence: GPL verze 2
 * Tento kod je poskytovan bez jakekoli zaruky.
 *
 * Pouziti: ./upvs2 soubor.upvs
 */

#include "upvs2.h"

/* Alokuje operacni pamet a ozadane velikosti, inicializuje ji vychozi hodnotou a vrati na ni ukazatel 
 * Pokud dojde k chybe, ukonci beh programu */
char * upvs2_mem_alloc(int size)
{
	char * ram = (char *)malloc(size);
	if (ram == NULL) {
		printf("%s\n", MEM_ERR_MSG);
		exit(EXIT_FAILURE);
	}

	for (int i = 0; i < RAM_SIZE; i++) {
		ram[i] = 0;
	}

	return ram;
}

/* Nacte zadany soubor do ramky virtualniho stroje */
void upvs2_load_program(char * ram, char * filename)
{
	int fp = open(filename, 0);
	if (fp == -1) {
		printf("%s\n", BAD_ARGUMENT_MSG);
		exit(EXIT_FAILURE);
	}

	char c;
	int i = 0;
	while (read(fp, (char*)&c, 1) != 0) {
		ram[i] = c;
	}
	
	close(fp);
}

int main(int argc, char * argv[])
{
	/* Kontrola poctu parametru */
	if (argc < 2) {
		printf("%s\n", FEW_ARGUMENTS_MSG);
		exit(EXIT_FAILURE);
	}

	/* Kontrola spravnosti zadaneho jmena souboru */
	int fd = open(argv[1], 0);
	if (fd == -1) {
		printf("%s\n", BAD_ARGUMENT_MSG);
		exit(EXIT_FAILURE);
	}
	close(fd);

	printf("UPVS 2\nVerze: %s\nCopyright (c) Martin Kumst 2010, 2011\n\n%s\n", VERSION, STARTING_MSG);
	
	/* Alokace operacni pameti pro virtualni stroj */
	char * ram = upvs2_mem_alloc(RAM_SIZE);

	/* Nacteni souboru s programem a jeho nahrani do operacni pameti virtualniho stroje */
	upvs2_load_program(ram, argv[1]);
	
	return 0;
}
